//const baseUrl = 'http://182.92.135.91:9090';
//const baseUrl = 'http://127.0.0.1:4523/m1/6873571-6588589-default'
// const baseUrl = 'http://111.228.44.41:9090'
const baseUrl = 'https://szymogu.top:9090'
//const baseUrl='https://anpu-tour-196523-5-1384941973.sh.run.tcloudbase.com'
//const baseUrl = 'http://vcccfenl.anpu-tour.n4kj3hm0.25txp1mf.com'
/**
 */
const request = (url, method = 'GET', data = {}, header = {}) => {
    //显示加载中
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    
    //构建请求头,添加JWT认证
    const token = wx.getStorageSync('token');
    const defaultHeader = {
        'Content-Type': 'application/json',
        ...(token && {'Authorization': `${token}`})
    };

    const finalHeader = { ...defaultHeader, ...header };

    return new Promise((resolve, reject) => {
        wx.request({
          //测试的url，后面需要加上baseUrl
          url: baseUrl + url,
          method,
          data,
          header: finalHeader,
          success: (res) => {
              wx.hideLoading();

              if(res.statusCode === 200) {
                  if(res.data.code === 200){
                      resolve(res.data.data);
                  }else{
                      wx.showToast({
                        title: res.data.msg || '请求失败',
                        icon: 'none'
                      })
                      reject(res.data);
                  }
              }else if(res.statusCode === 401){
                wx.removeStorageSync('token')
                wx.navigateTo({
                    url: '/pages/home/home',
                });
                reject(new Error('登录过期,请重新登录'));
                return;
              }else{
                  wx.showToast({
                    title: `网络错误${res.statusCode}`,
                  });
                  reject(res);
              }
          },
          fail: (err) => {
              wx.hideLoading();
              wx.showToast({
                title: '网络请求失败',
              });
              reject(err)
          }
        });
    });
};

module.exports = {
    get: (url, data, header) => request(url, 'GET', data, header),
    post: (url, data, header) => request(url, 'POST', data, header),
    put: (url, data, header) => request(url, 'PUT', data, header),
    delete: (url, data, header) => request(url, 'DELETE', data, header),
    baseUrl:baseUrl
};